import { useAuthStore } from '@/stores/auth-store'
import { useRoute, useRouter } from 'vue-router'
import { iframeTaskMitt } from '@/utils/tools/bus'

// 根据用户登录状态，跳转不同页面
export const authGuard = async to => {
  const route = useRoute()
  const router = useRouter()
  const { sessionId = '', userId = '' } = route.query
  if (sessionId && userId) {
    return
  }
  const { userInfo } = useAuthStore()
  if (to.path === '/login' && userInfo.userId) {
    router.push('/')
    return
  }
  if (to.path === '/login' || to.path === '/pad-graph') {
    return
  } else {
    if (!userInfo.userId) {
      // ElMessage.error('请先登录')
      router.push('/login')
    }
  }
}

// 别的平台跳转到本平台，会传递query参数过来
export const otherPlatformGuard = async () => {
  const { handleLoginInfo } = useAuthStore()
  const route = useRoute()

  const { sessionId = '', userId = '' } = route.query
  if (sessionId && userId) {
    await handleLoginInfo(route.query)
    location.search = ''
    return
  }
}

export const questionBankEmitGuard = async (to, from) => {
  if (
    from.path.includes('/question-bank/') &&
    !to.path.includes('/question-bank/')
  ) {
    iframeTaskMitt.emit('toggle-topic-selector-dialog', false)
  }
}
